var App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      // 门店下拉
      dataList:[],
      domain:App.globalData.iconsUrl,
      imgShow:{},
      imgIndex:{},
      // 门店下拉
      storeList:[],
      storeindex:0,  //下标
      store_name:'', //选中回显
      store_id:'',    //选中的门店ID
      // s
      submitUrl:'',
  },
    
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //检测是否登录
    App.checkIsLogin()
    // 获取门店列表
    this.getData()
    this.getStore()
  },
  // 获取门店下拉列表
  getStore(){
    let that = this
    let obj = {b_id:App.get_b_id()}
    App.request('/Manage/Management/storeList',obj,function(e){
        if (e.code == "200") {that.setData({storeList:e.result})}
    })
  },
  // 获取门店列表
  getData(){
    let that = this
    let obj = {
      b_id:App.get_b_id(),
      store_id:that.data.store_id
    }
    App.request('/Manage/Management/settingStoreList',obj,function(e){
      wx.stopPullDownRefresh()
       let imgShow = {}
       let imgIndex = {}
       e.result.forEach(element => {
         imgShow["img"+element.store_id] = element.store_license
         imgIndex["img"+element.store_id] = 10
       });
        if (e.code == "200") {
          that.setData({
            dataList:e.result,
            imgShow,
            imgIndex
          })
        }
    })
  },
  //选择店铺
  bindStorePicker: function (e) {
    this.setData({
      storeindex: e.detail.value,
      store_id:this.data.storeList[e.detail.value].store_id,
      store_name:this.data.storeList[e.detail.value].title,
    })
     this.getData()//获取数据列表
  },
  // 选择要展示图片
  showImg(e){
    // console.log('imgShow',this.data.imgShow)
    let imgShow = this.data.imgShow
    let imgIndex = this.data.imgIndex
    let id = e.currentTarget.dataset.id;
    let url = e.currentTarget.dataset.url;
    let index = e.currentTarget.dataset.index;
    imgShow["img"+id] =url
    imgIndex["img"+id] =index
    this.setData({
      imgShow,
      imgIndex
    })
  },
  uploadPhoto(e) {
    let id=e.currentTarget.dataset.id;
    let index=e.currentTarget.dataset.index;
    var that = this; 
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(res);
        // 判断图片不能超过2M
        if (res.tempFiles[0].size > 1024 * 2048) {
          wx.showToast({
              title: '图片请控制在200KB以内', //标题
              icon: 'none' //图标 none不使用图标，详情看官方文档
          })
          return;
        }else{
          // 如果超过512KB压缩一下
          if (1==1) {
              // 调用压缩方法
              that.uploadCompressImg(res.tempFiles[0]).then(res=>{
                App.uploadFile(res,{store_id:id,image:index},function(result){
                  // that.setData({
                  //   submitUrl:result.result.url
                  // })
                  that.getData();
                })
              })
          }
        }
      }
    })
  },
  //图片压缩
  uploadCompressImg(file) {
    console.log(file)
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.path
      console.log(file);
      if(file.size < 512*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
          // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
// 获取门店列表
this.getData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})